<template>
  <div style="padding: 10px">
    <t-loading :loading="loading" :text="loadingText" fullscreen />

    <t-card title="PBOM">
      <div style="display: flex">
        <t-form label-align="right" layout="inline" label-width="80px">
          <t-form-item label="BOM版本" name="FNumber">
            <t-input v-model="formData.FNumber" placeholder="请输入料号" />
          </t-form-item>
          <t-form-item label="材料编号" name="FMATERIALID">
            <t-input v-model="formData.FMATERIALID" placeholder="请输入材料编号" />
          </t-form-item>
          <t-form-item label="站别" name="F_ora_Remark">
            <t-input v-model="formData.F_ora_Remark" placeholder="请输入站别" />
          </t-form-item>
        </t-form>

        <t-space align="end" style="align-self: flex-end">
          <t-button theme="primary" @click="clickQuery">查询</t-button>
        </t-space>
      </div>
    </t-card>

    <t-card title="">
      <t-space align="end" style="display: flex; justify-content: center">
        <t-button variant="outline" theme="primary" @click="clickBuy">物料申购</t-button>
        <t-button variant="outline" theme="primary" @click="clickSave">暂存</t-button>
      </t-space>
    </t-card>

    <div style="margin-top: 10px; display: flex; flex-direction: column">
      <t-space style="display: flex; background-color: white; padding: 10px 10px">
        <t-link theme="primary" @click="clickUpload">上传excel</t-link>
        <t-link theme="primary" @click="clickExport">excel导出</t-link>
        <t-link theme="primary" @click="clickAdd">新增</t-link>
        <!-- <t-popconfirm content="确认删除吗" @confirm="clickDelPbom">
          <t-link theme="primary" @click="delRow">删除行</t-link>
        </t-popconfirm> -->
      </t-space>

      <t-table
        row-key="id"
        :data="dataList"
        :columns="columns"
        :resizable="true"
        :loading="tableLoading"
        :stripe="stripe"
        :selected-row-keys="selectedRowKeys"
        :active-row-type="single"
        :select-on-row-click="true"
        bordered
        :hover="true"
        table-layout="auto"
        size="small"
        :pagination="pagination"
        cell-empty-content="-"
        resizable
        lazy-load
        @select-change="rehandleSelectChange"
      >
        <template #FNumber="{ rowIndex, row }">
          <t-link theme="primary" @click="handleRowClick($event, rowIndex, row)">
            {{ row['FNumberShow'] ? row['FNumber'] : '' }}
          </t-link>
        </template>

        <template #FBOMCATEGORY_NAME="{ rowIndex, row }">
          <span style="">{{ row['FNumberShow'] ? row['FBOMCATEGORY_NAME'] : '' }}</span>
        </template>

        <template #FMaterialNumber="{ rowIndex, row }">
          <span style="">{{ row['FNumberShow'] ? row['FMaterialNumber'] : '' }}</span>
        </template>

        <template #FITEMNAME="{ rowIndex, row }">
          <span style="">{{ row['FNumberShow'] ? row['FITEMNAME'] : '' }}</span>
        </template>

        <template #FITEMMODEL="{ rowIndex, row }">
          <span style="">{{ row['FNumberShow'] ? row['FITEMMODEL'] : '' }}</span>
        </template>

        <template #FDocumentStatusName="{ rowIndex, row }">
          <span style="color: dodgerblue">{{ row['FDocumentStatusName'] }}</span>
        </template>

        <!-- <template #ellipsis-FCHILDITEMMODEL="{ row, col }">
          <span>插槽定义浮层内容：{{ row[col.colKey] }}</span>
        </template> -->

        <template #operation="{ row }">
          <t-button theme="primary" hover="color" @click="handleClickEdit($event, row)"> 编辑 </t-button>
        </template>
      </t-table>
    </div>

    <detail ref="detailRef" @update-data="loadData" />

    <uploadDialog
      ref="uploadRef"
      :dl-url="filePrefix + '物料清单模板.xlsx'"
      :upload-url="API_URL + 'pbom/uploadPbomParent'"
      @upload-success="clickQuery"
    />
  </div>
</template>

<script lang="jsx">
import { ref, reactive, computed, onMounted } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { columns } from './columns/index';
import { queryPbomList, exportData, delPbom } from '@/service/pbom';

import Detail from './components/detail.vue';
import uploadDialog from '@/components/uploadDialog/index.vue';
import { filePrefix, API_URL } from '@/common/constants';

import { downloadRes } from '@/common/download';
import router from '@/router';

export default {
  components: { Detail, uploadDialog },
  setup(props) {
    const formData = reactive({ FMATERIALID: '' });
    // const formData = reactive({ FMATERIALID: 111204, FDocumentStatus: '', FName: '伺服电机' })
    const detailRef = ref();
    const uploadRef = ref();

    const total = ref(300);
    const loading = ref(false);
    const loadingText = ref('加载中...');

    const tableLoading = ref(false);
    const selectedRowKeys = ref([]);

    const curr_page = ref(1);
    const page_size = ref(20);

    const dataList = ref([]);
    const pagination = computed(() => {
      return {
        defaultCurrent: 1,
        defaultPageSize: page_size.value,
        total: total.value,
        onChange: (pageInfo) => {
          const { current, pageSize } = pageInfo;
          curr_page.value = current;
          page_size.value = pageSize;
          loadData();
        },
      };
    });

    const rehandleSelectChange = (value, { selectedRowData }) => {
      selectedRowKeys.value = value;
      console.log('rehandleSelectChange', selectedRowData);
    };
    const handleRowClick = (e, rowIndex, row) => {
      e.stopPropagation();

      router.push({ name: 'pbomEdit', params: { id: row.FNumber } });
    };

    const clickQuery = () => {
      curr_page.value = 1;
      loadData();
    };

    const handleClickEdit = (e, row) => {
      console.log(e);

      e.stopPropagation();
      router.push({ name: 'pbomEdit', params: { id: row.FNumber } });
    };

    const clickAdd = () => {
      router.push({ name: 'pbomAdd' });
    };

    const clickExport = async () => {
      loadingText.value = '正在导出...';
      loading.value = true;
      try {
        const res = await exportData({
          ...formData,
          // curr_page: curr_page.value,
          // page_size: page_size.value,
        });
        downloadRes('PBOM', res);
      } catch (error) {}
      loading.value = false;
    };
    const clickSave = () => {};
    const clickBuy = () => {
      if (!selectedRowKeys.value[0]) {
        MessagePlugin.closeAll();
        MessagePlugin.error('未选择行！');
        return;
      }
      router.push({
        name: 'materSubscribe',
        params: {
          isMbom: 'N',
          bomIds: selectedRowKeys.value.join(','),
        },
      });
    };

    const loadData = async () => {
      tableLoading.value = true;
      const res = await queryPbomList({
        ...formData,
        curr_page: curr_page.value,
        page_size: page_size.value,
      });
      dataList.value = res.dataList;

      if (dataList.value[0]) {
        let last_fnumber = null;
        let item_index = 1;
        for (let index = 0; index < dataList.value.length; index++) {
          const item = dataList.value[index];
          if (!last_fnumber || last_fnumber != item.FNumber) {
            item.FNumberShow = true;
            item_index = 1;
          }
          item.index = item_index;
          last_fnumber = item.FNumber;

          item_index++;
        }
        total.value = res.total;
      } else {
        dataList.value = [];
        total.value = 0;
      }

      // total.value = res.length;

      tableLoading.value = false;
    };

    const clickUpload = () => {
      uploadRef.value.openExcelDialog();
    };

    const clickDelPbom = async () => {
      if (selectedRowKeys.value.length == 0) {
        MessagePlugin.error('未选择行！');
        return;
      }
      fnumbers = dataList.value.filter((item) => selectedRowKeys.value.indexOf(item.FMATERIALID) >= 0);
      const res = await delPbom(fnumbers.join(','));
      if (res.success) {
        loadData();
      } else {
        MessagePlugin.error(`删除失败:${res.msg}`);
      }
    };

    onMounted(() => {
      loadData();
    });

    return {
      detailRef,
      uploadRef,
      columns,
      pagination,
      total,
      formData,
      dataList,
      loadData,
      handleClickEdit,
      loading,
      loadingText,
      tableLoading,
      clickAdd,
      handleRowClick,
      curr_page,
      page_size,
      selectedRowKeys,
      rehandleSelectChange,
      clickUpload,
      filePrefix,
      API_URL,
      clickExport,
      clickBuy,
      clickSave,
      clickDelPbom,
      clickQuery,
    };
  },
};
</script>
